package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.Notice;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-19
 */
@RestController
@RequestMapping("/notice")
public class NoticeController extends BaseController {
    @GetMapping("/list")
    public Result list(String title) {
        Page<Notice> pageData = noticeService.page(getPage(), new QueryWrapper<Notice>()
                .like(StrUtil.isNotBlank(title), "title", title).orderByDesc("create_time"));

        pageData.getRecords().forEach(n -> {
            n.setUser(sysUserService.getById(n.getUserId()));
        });

        return Result.success(pageData);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        Notice notice = noticeService.getById(id);

        notice.setUser(sysUserService.getById(notice.getUserId()));

        return Result.success(notice);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('notice:save')")
    public Result save(@RequestBody Notice notice) {
        noticeService.save(notice);

        notice.setUser(sysUserService.getById(notice.getUserId()));

        return Result.success(notice);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('notice:update')")
    public Result update(@RequestBody Notice notice){
        noticeService.updateById(notice);

        notice.setUser(sysUserService.getById(notice.getUserId()));

        return Result.success(notice);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('notice:delete')")
    public Result delete(@RequestBody Long[] ids) {
        noticeService.removeByIds(Arrays.asList(ids));

        return Result.success("");
    }
}
